import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/model/love_record_model.dart' as LRModel;
import 'package:love_app/pages/love_record/love_record_ui/image_length_ui.dart';
import 'package:love_app/providers/love_record_item_provider.dart';
import 'package:love_app/providers/love_record_provider.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/routes/application.dart';
import 'package:love_app/service/love_record_api.dart';
import 'package:love_app/style/space_header.dart.dart';
import 'package:provider/provider.dart';

// 恋爱记录的内容
class Centent extends StatefulWidget {
  @override
  _CententState createState() => _CententState();
}

class _CententState extends State<Centent> {
  LoveRecordProvider _loveRecordProvider; // 共享
  ShareProvider _shareProvider;
  ScrollController _scrollController; // 滚动条监听控制器
  EasyRefreshController _easyRefreshController; // 加载控制器

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loveRecordProvider =
        Provider.of<LoveRecordProvider>(context, listen: false);
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
  }

  @override
  void dispose() {
    _scrollController.dispose(); // 销毁控制器
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _afterBuild(context);
    // 异步加载widget
    return FutureBuilder(
      future: _statr(_shareProvider.token), // 异步事件（获取第一页数据）
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        // 异步加载完成后要进入的
        if (snapshot.connectionState == ConnectionState.done) {
          return Container(
            child: _pageContent(_scrollController),
            // child: Consumer<LoveRecordProvider>(
            //   builder: (BuildContext context, LoveRecordProvider provider, Widget child){
            //     return _pageContent(_scrollController);
            //   },
            // ),
          );
        } else {
          // 还没有完成异步加载要显示
          // return SuDialog.futureBuildLoding(
          //     textColor: _shareProvider.textColor);
          return Container();
        }
      },
    );
  }

  // 进行一系列初始化
  void _afterBuild(BuildContext context) {
    // 获取恋爱记录
    _scrollController =
        ScrollController(initialScrollOffset: _loveRecordProvider.offset);

    LoveRecordItemProvider loveRecordItemProvider =
        Provider.of<LoveRecordItemProvider>(context, listen: false);

    // 添加滚动条位置监听
    _scrollController.addListener(() {
      _loveRecordProvider.offset = _scrollController.offset;
      // 通过监听滚动条位置，改变恋爱记录顶部item状态
      if (_scrollController.offset > 200.0) {
        // 字体消失，图标大小变为二分之一
        loveRecordItemProvider.opacityData = 0.0;
        loveRecordItemProvider.imageSize = Su().w(47);
      } else {
        loveRecordItemProvider.opacityData = 1.0;
        loveRecordItemProvider.imageSize = Su().w(94);
      }
      loveRecordItemProvider.notify();
    });
  }

  // 异步加载widget完成后进入的widget
  Widget _pageContent(ScrollController scrollController) {
    // 获取保存在共享中的widget
    // List<Widget> widgets = _loveRecordProvider.widgets;
    // List<LRModel.Data> allItemData = _loveRecordProvider.getItemData();
    // 监听滚动位置
    return EasyRefresh.custom(
      scrollController: scrollController,
      controller: _easyRefreshController,
      bottomBouncing: true,
      header: SpaceHeader(),
      enableControlFinishLoad: true,
      onRefresh: () async {
        // 触发下拉刷新
        _loveRecordProvider.clean(); // 清除共享provider内容
        _loveRecordProvider.notify();
        // setState(() {
        // });
      },
      onLoad: () async {
        // 触发上拉加载
        await _onLoad(scrollController);
      },
      slivers: <Widget>[
        Consumer<LoveRecordProvider>(
          builder: (BuildContext context, LoveRecordProvider provider,
              Widget child) {
            List<LRModel.Data> allItemData = provider.getItemData();
            return SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              Widget item =
                  BuildItem(textShowAll: false).everyItem((allItemData[index]));
              int id = allItemData[index].id; // 数据库对应的id
              return InkWell(
                onTap: () {
                  Application.router
                      .navigateTo(context, "/detailsItem?itemID=$id");
                },
                child: item,
              );
            },
            childCount: allItemData.length,
          ),
        );
          },
        ),
        // SliverList(
        //   delegate: SliverChildBuilderDelegate(
        //     (context, index) {
        //       Widget item =
        //           BuildItem(textShowAll: false).everyItem((allItemData[index]));
        //       int id = allItemData[index].id; // 数据库对应的id
        //       return InkWell(
        //         onTap: () {
        //           Application.router
        //               .navigateTo(context, "/detailsItem?itemID=$id");
        //         },
        //         child: item,
        //       );
        //     },
        //     childCount: allItemData.length,
        //   ),
        // ),
      ],
    );
  }

  // 触发上拉加载
  Future<void> _onLoad(ScrollController scrollController) async {
    int page = _loveRecordProvider.nextPage();
    try {
      if (_loveRecordProvider.isEndPage == false) {
        LRModel.LoveRecordModel loveRecordModel = await LoveRocordApi()
            .getLoveRecord(_shareProvider.token, page: page);
        _buildListItem(loveRecordModel);
        _loveRecordProvider.addPage();
        if (loveRecordModel.data.length == 0) {
          // 如果放回的data长度为0， 则没有下一页
          _loveRecordProvider.isEndPage = true;
          _easyRefreshController.finishLoad(success: true, noMore: true);
        } else {
          // 保存当前的当前的加载位置
          // setState(() {
          // });
          _easyRefreshController.finishLoad(success: true, noMore: true);
          _loveRecordProvider.notify();
        }
      }
    } catch (error) {
      SuDialog.showToast("加载异常");
    }
  }

  // 异步widget加载初始化
  Future<void> _statr(String token) async {
    // 判断provider有没有内容
    if (_loveRecordProvider.itemData.length == 0) {
      LRModel.LoveRecordModel loveRecordModel =
          await LoveRocordApi().getLoveRecord(token, page: 1); // 获取api返回的List内容
      // 没有内容则进行初始化
      _buildListItem(loveRecordModel);
    }
  }

  // 往共享模型添加数据
  void _buildListItem(LRModel.LoveRecordModel loveRecordModel) {
    List<LRModel.Data> loveRecordData = loveRecordModel.data;
    _loveRecordProvider.setItemData(loveRecordData);
  }
}

// 生成每一个item
class BuildItem {
  final bool textShowAll; // 是否显示全部字体

  BuildItem({@required this.textShowAll});

  // 每一个item的内容
  Widget everyItem(LRModel.Data loveRecordItemData) {
    return Container(
      width: Su().w(750),
      margin: EdgeInsets.only(
        top: Su().h(14),
      ),
      child: Column(
        children: <Widget>[
          _itemHeader(loveRecordItemData),
          _mainCentent(loveRecordItemData),
        ],
      ),
    );
  }

  // 每一个动态头部
  Widget _itemHeader(LRModel.Data loveRecordItemData) {
    String headerImagePath = loveRecordItemData.userInfo.headImg;
    String timeStamp = loveRecordItemData.dynamicTime.toString();
    return Container(
      height: Su().h(92),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(
            color: Colors.white,
          )),
      child: Row(
        children: <Widget>[
          _itemHeaderImage(headerImagePath),
          _itemHeaderDate(timeStamp),
        ],
      ),
    );
  }

  // 头像��式
  Widget _itemHeaderImage(String headerImagePath) {
    return Padding(
      padding: EdgeInsets.only(
        top: Su().h(31),
        left: Su().w(29),
      ),
      child: ClipOval(
        child: new Image.network(
          headerImagePath,
          width: Su().w(60),
          height: Su().w(60),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  // 时间
  Widget _itemHeaderDate(String timeStamp) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: EdgeInsets.only(
            top: Su().h(42),
            left: Su().w(27),
          ),
          child: Text(
            Su().getDate(timeStamp),
            style: Su().textStyle(Color.fromRGBO(179, 179, 179, 1), 20),
          ),
        ),
      ],
    );
  }

  // item的主体内容
  Widget _mainCentent(LRModel.Data loveRecordItemData) {
    return Container(
      color: Colors.white,
      width: Su().w(750),
      padding: EdgeInsets.only(
        left: Su().w(31),
        right: Su().w(31),
      ),
      child: Column(
        children: <Widget>[
          _mainItemText(loveRecordItemData.content),
          _mainItemImages(
              loveRecordItemData.pictures, loveRecordItemData.id.toString()),
        ],
      ),
    );
  }

  // 文字部分
  Widget _mainItemText(String text) {
    // 根据textShowAll来显示是否要现在行数
    Widget textWidget = textShowAll == true
        ? Text(
            text,
            style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 28),
          )
        : Text(
            text,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 28),
          );
    return Container(
      alignment: Alignment.topLeft,
      padding: EdgeInsets.only(
        bottom: Su().h(10),
      ),
      child: textWidget,
      color: Colors.white,
    );
  }

  // 图片部分
  Widget _mainItemImages(List<LRModel.Pictures> imagesList, String itemId) {
    ImageLengthUI ui = ImageLengthUI(imagesList: imagesList, itemId: itemId);
    // Widget imagesUI = ui.imageUI();
    return Container(
      padding: EdgeInsets.only(
        bottom: Su().h(10),
      ),
      child: ui,
    );
  }
}
